package com.itheima.reggie.contreller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook){
        //当前登录用户id
        Long userid = BaseContext.getCurrentId();

        addressBook.setUserId(userid);
        addressBookService.save(addressBook);
        return R.success("添加成功");
    }

    @GetMapping("/list")
    public R<List<AddressBook>> list(){
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        List<AddressBook> list = addressBookService.list(queryWrapper);
        return R.success(list);
    }
    @PutMapping("/default")
    public R<String> setdefault(@RequestBody AddressBook addressBook){
        //先把所有地址设置成0

        LambdaUpdateWrapper<AddressBook> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        queryWrapper.set(AddressBook::getIsDefault,0);
        addressBookService.update(queryWrapper);
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return R.success("修改成功");
    }

    @GetMapping("/default")
    public R<AddressBook> getDefault(){
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        queryWrapper.eq(AddressBook::getIsDefault,1);
        AddressBook book = addressBookService.getOne(queryWrapper);
        if (book!=null){
            return R.success(book);
        }else {
            return R.error("没有默认地址");
        }

    }

    @DeleteMapping
    public R<String> delete(Long ids){
    addressBookService.removeById(ids);
    return R.success("删除成功");
    }

    @GetMapping("/{id}")
    public R<AddressBook> getid(@PathVariable Long id){
        if (id!=null) {
            AddressBook addressBook = addressBookService.getById(id);
            return R.success(addressBook);
        }else{
            return R.error("暂无信息");
        }
    }

    @PutMapping
    public R<String> updat(@RequestBody AddressBook addressBook){
            addressBookService.updateById(addressBook);
            return R.success("修改成功");
    }
}
